<template>
  <view class="cart-component">
    <view class="shop-cart-btn">
      <view class="left" style="display: flex">
        <view class="cart-icon">
          <image
            @click="openCart"
            class="imgse"
            :fade-show="false"
            :src="require('@/static/user/food-icona.png')"
          >
          </image>
          <view v-if="allNum" class="cart-num">{{ allNum }}</view>
        </view>
        <text>
          <text style="font-size: 28rpx">合计：</text>
          <text style="font-size: 40rpx">{{ `￥${allPrice}` }}</text>
        </text>
      </view>

      <view class="right" v-if="isOrder" @click="submitOrder">立即支付</view>
      <view
        class="right"
        v-else-if="!isOrder && cartList.length"
        @click="toSubmitFood"
        >去结算</view
      >
      <view class="right noText" v-else>未点餐</view>
    </view>
    <uni-popup
      background-color="#ffffff"
      ref="cartPop"
      type="bottom"
      borderRadius="10px 10px 10px 10px"
    >
      <view class="cart-pop">
        <view class="clear-text" @click="clearCart"> 清空购物车 </view>
        <view class="cart-content">
          <view
            v-for="(item, index) in cartList"
            :key="item.id"
            class="scroll-view-item uni-bg-red goods-item"
          >
            <view
              class="img cart-img"
              :style="{
                backgroundImage: `url(${foodFile + item.thumbnail})`,
              }"
            >
            </view>
            <view class="text infos">
              <view class="title">{{ item.name }}</view>
              <view class="remark">x{{ item.number || "" }}</view>
              <view class="price-add flex-between">
                <text class="price">{{
                  item.price ? `￥${item.price}` : ""
                }}</text>
                <view class="add-sub flex-between">
                  <view
                    class="add-sub-btn flex-center sub-btn"
                    @click.stop="handleSub(item)"
                    >-</view
                  >
                  <text style="margin: 0 20rpx">{{ item.number }}</text>
                  <view
                    class="add-sub-btn flex-center add-btn"
                    @click.stop="handleAdd(item)"
                    >+</view
                  >
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  submitFoodOrder,
  payTradeByUser,
  payTradeByStaffByOrderId,
} from "@/api/foodPage.js";
export default {
  data() {
    return {
      payList: [],
      foodFile: uni.getStorageSync("foodFile"),
      payTime: null,
    };
  },
  props: { isOrder: { type: Boolean, default: false } },
  computed: {
    cartList() {
      return this.$store.state.user.cartList;
    },
    allNum() {
      const result = this.cartList.reduce((pre, cur) => {
        pre += cur.number;
        return pre;
      }, 0);
      return result;
    },
    allPrice() {
      if (!this.cartList || !this.cartList.length) {
        return "0.00";
      }

      const result = this.cartList.reduce((pre, cur) => {
        pre += (cur.number || 0) * cur.price;
        return pre;
      }, 0);
      return result ? Number(result).toFixed(2) : "0.00";
    },
  },

  methods: {
    clearCart() {
      this.$store.dispatch("user/handleSetCardList", []);
      this.$refs.cartPop.close();
    },
    openCart() {
      if (!this.cartList.length) return;
      this.$refs.cartPop.open();
    },
    submitOrder() {
      uni.showModal({
        title: "提示",
        content: "是否确认提交订单？",
        success: ({ confirm }) => {
          if (confirm) {
            this.confirmSubmit();
          }
        },
      });
    },
    async confirmSubmit() {
      const totalPrice = this.cartList
        .reduce((pre, cur) => {
          pre += cur.number * cur.price;
          return pre;
        }, 0)
        .toFixed(2);
      const params = {
        food: true,
        foodTableNo: uni.getStorageSync("tableNo"),
        goodsDTOList: this.cartList.map((v) => {
          return {
            goodsId: v.id,
            goodsName: v.name,
            number: v.number,
            orderType: "FOOD",
          };
        }),
        goodsFee: totalPrice,
        payFee: totalPrice,
        receivableFee: totalPrice,
        orgId: uni.getStorageSync("foodOrgId") || "",
        storeId: uni.getStorageSync("storeId") || "",
      };
      console.log(params, "parasm-----------------");
      const res = await submitFoodOrder(params);
      this.creatPayOrder(res.body, params);
    },
    async creatPayOrder(orderInfo, query) {
      const params = {
        orderFatherId: orderInfo.id,
        payFee: query.payFee,
        payMethod: "WX",
      };
      const { body } = await payTradeByUser(params);
      if (!body.payInfo) return;
      const payInfo = JSON.parse(body.payInfo);
      uni.requestPayment({
        //微信支付
        provider: "wxpay",
        timeStamp: payInfo.timeStamp,
        nonceStr: payInfo.nonceStr,
        package: payInfo.packageValue,
        signType: payInfo.signType,
        paySign: payInfo.paySign,
        success: async (res) => {
          uni.showToast({
            title: "支付成功",
          });
          uni.showLoading({
            title: "正在查询支付结果...",
          });
          this.$store.dispatch("user/handleSetCardList", []);
          setTimeout(() => {
            // await this.validatePayState(orderInfo.id);
            uni.hideLoading();
            uni.redirectTo({
              url: `/pages/orderPage/index?type=1`,
            });
          }, 3000);
        },
        fail(err) {
          uni.showToast({
            title: "支付失败",
            icon: "error",
          });
        },
      });
    },
    toSubmitFood() {
      uni.navigateTo({
        url: "/pages/foodPage/order",
      });
    },
    handleAdd(item) {
      const cartList = this.cartList;
      const res = cartList.some((v) => v.id === item.id)
        ? cartList.map((v) => ({
            ...v,
            number: v.id === item.id ? (v.number || 0) + 1 : v.number,
          }))
        : [...cartList, { ...item, number: 1 }];
      this.$store.dispatch("user/handleSetCardList", res);
    },
    handleSub(item) {
      const cartList = this.cartList;
      const res = cartList
        .map((v) => ({
          ...v,
          number: item.id === v.id ? v.number - 1 : v.number,
        }))
        .filter((v) => v.number > 0);
      this.$store.dispatch("user/handleSetCardList", res);
      if (res.length <= 0) {
        this.$refs.cartPop.close();
      }
    },
    onHide() {
      clearInterval(this.payTime);
      this.payTime = null;
    },
    validatePayState(id) {
      return new Promise(async (resolve, reject) => {
        const res = await payTradeByStaffByOrderId({ id });
        if (res.code == 0) {
          if (res.body == "USERPAYING") {
            // 没有数据 继续请求
            this.payTime = setInterval(() => {
              this.validatePayState(id);
            }, 2000);
            return;
          }
          if (res.body == "SUCCESS") {
            clearInterval(this.payTime);
            this.payTime = "";
            resolve(1);
          }
        } else {
          reject(1);
          uni.showToast({
            title: "支付失败",
            icon: "none",
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.shop-cart-btn {
  width: 700rpx;
  height: 100rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  bottom: 30rpx;
  margin: 0 auto;
  margin-left: 25rpx;
  z-index: 999;
  .left {
    height: 100rpx;
    flex: 1;
    padding: 0 20rpx;
    border-bottom-left-radius: 44rpx;
    border-top-left-radius: 44rpx;
    background-color: #333333;
    color: #fff;
    display: flex;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
  }
  .right {
    height: 100rpx;
    width: 200rpx;
    padding: 0 20rpx;
    border-bottom-right-radius: 44rpx;
    border-top-right-radius: 44rpx;
    background-color: #5cc39d;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.imgse {
  width: 52upx;
  height: 52upx;
  margin-right: 10rpx;
}
.noText {
  background-color: #333;
  color: #999;
}
.cart-icon {
  position: relative;
  .cart-num {
    width: 36rpx;
    position: absolute;
    top: -16rpx;
    right: -4rpx;
    background-color: red;
    color: #fff;
    line-height: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    height: 36rpx;
    border-radius: 50%;
    font-size: 20rpx;
  }
}
.goods-item {
  display: flex;
  padding: 10rpx 0;
  .img {
    width: 140rpx;
    height: 140rpx;
    margin-right: 20rpx;
    background-color: #f2f2f2;
    border-radius: 10rpx;
    flex-shrink: 0;
    background-size: cover;
    background-repeat: no-repeat;
  }
  .infos {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10rpx 0;
    .title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
    .remark {
      font-size: 20rpx;
      color: #666;
    }
    .price-add {
      .price {
        font-size: 30rpx;
        color: #da3946;
        font-weight: bold;
      }
      .add-sub-btn {
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #5cc39d;
      }
      .sub-btn {
        background-color: #fff;
        border: 1px solid #5cc39d;
        line-height: 44rpx;
      }
      .add-btn {
        color: #fff;
      }
    }
  }
}
.cart-pop {
  background-color: #fff;
  border-radius: 40rpx;
  padding: 30rpx;
  padding-bottom: 108rpx;

  .clear-text {
    color: #999;
    margin: 20rpx 0;
    text-align: center;
    margin-bottom: 30rpx;
    display: flex;
    font-size: 24rpx;
    justify-content: flex-end;
  }
  .cart-content {
    max-height: 900rpx;
    overflow-y: auto;
  }
  .center {
    padding: 30rpx 0;
    width: 100%;
    background-color: #5cc39d;
    border-radius: 50rpx;
    .center-title {
      font-size: 36rpx;
      color: #333;
      font-weight: bold;
    }
    .msg {
      font-size: 24rpx;
      color: #999;
    }
  }
}
</style>
